<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
<input type="file" name="" id="upload">
</body>
<script>


  function convertImageToBase64(file, callback) { // 获取base64
    let reader = new FileReader()
    reader.addEventListener("load", e => {
      // console.log(e.target.result);
      console.log(reader);
      callback && callback(reader.result)
      reader = null;
    })
    reader.readAsDataURL(file);
  }

  function compress(base64Image, callback) { // 压缩
    const image = new Image()
    image.src = base64Image
    let maxW = 1024
    let maxH = 1024
    image.addEventListener("load", e => {
      let ratio;
      let needCompress = false;
      // console.log(image.namespaceURI, image.naturalWidth);
      if(maxW < image.naturalWidth) {
        needCompress = true;
        ratio = image.naturalWidth / maxW
        maxH = image.naturalHeight / ratio
      }
      if(maxH < image.naturalHeight) {
        needCompress = true;
        ratio = image.naturalHeight / maxH
        maxW = image.naturalWidth / ratio
      }
      if(!needCompress) {
        maxH = image.naturalHeight
        maxW = image.naturalWidth
      }
      const canvas = document.createElement("canvas")
      canvas.setAttribute("id", "__compress__")
      canvas.width = maxW
      canvas.height = maxH
      // canvas.style.visibility = "hidden"
      canvas.style.visibility = "visible"
      document.body.appendChild(canvas)
      const ctx = canvas.getContext("2d")
      ctx.clearRect(0, 0, maxW, maxH)// 清除画布
      ctx.drawImage(image, 0, 0, maxW, maxH)
      const compressImage = canvas.toDataURL("image/ipeg", 0.8)
      // console.log(compressImage);
      callback && callback(compressImage)
    })
    document.body.appendChild(image)
  }

  const ACCEPT = ['image/jpeg', 'image/png', "image/jpg", "image/webp"];
  const upload = document.getElementById("upload")
  upload.addEventListener("change", function (e) {
    // console.log(e.target.files[0]);
    const [file] = e.target.files;
    if (!file) {
      return;
    }
    const {type: fileType, size: fileSize} = file;
    if (!ACCEPT.includes(fileType)) {
      alert(`不支持${fileType}文件类型`)
      return
    }
    if (fileSize > 1024 * 1024 * 5) {
      alert("文件超出1mb")
      return
    }
    convertImageToBase64(file, (base64Image) => {compress(base64Image, uploadToServer)})
    function uploadToServer(compressImage) {// 最终获得回调函数
      console.log(compressImage);
      console.log("upload to server");
    }
  })
</script>

</html>
